package com.rainbow.redis.plus.core.context;

import javax.annotation.PostConstruct;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.rainbow.redis.plus.core.constant.RedisConstant;

public class ContextApplicationContextAware implements ApplicationContextAware {
	
    private Environment environment;
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;

	@SuppressWarnings("unchecked")
	@PostConstruct
    public void initRedisClientName() {
		String clientNameCommand = "CLIENT";
		String clientName = environment.getProperty(RedisConstant.PROJECT_NAME, String.class, RedisConstant.UNKNOWN)
				+ "_" + environment.getProperty(RedisConstant.PROJECT_UUID, String.class, RedisConstant.UNKNOWN);
		RedisCallback<Object> callback = (connection) -> connection.execute(clientNameCommand,"SETNAME".getBytes(),clientName.getBytes());
        redisTemplate.execute(callback);
    }

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.environment = applicationContext.getEnvironment();
	}
}
